package webengine

import (
	"runtime"
	"strings"

	"github.com/gin-gonic/gin"

	"gin-api-server/core_library/global"
	"gin-api-server/core_library/library/webengine/resp"
)

func PrintStack() string {
	var buf [4096]byte
	n := runtime.Stack(buf[:], false)
	return string(buf[:n])
}

func Recover(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			backErrInfoData := map[string]any{
				"errMsg": errorToString(err),
			}
			errDataMesage := PrintStack()
			serverDebug := global.Config.Server.Debug
			if serverDebug {
				errDataMesage = strings.ReplaceAll(errDataMesage, "\t", "   ")
				backErrInfoData["errData"] = strings.Split(errDataMesage, "\n")
			}
			resp.FailWithDataAndMsg(c, "程序异常", backErrInfoData)
		}
	}()
	c.Next()

}

// recover错误，转string
func errorToString(r interface{}) string {
	switch v := r.(type) {
	case error:
		return v.Error()
	default:
		return r.(string)
	}
}
